package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.Supplier;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.dao.SupplierRepository;
import com.yegs.jltqc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SupplierServiceImpl implements
        SupplierService {

    @Autowired
    private SupplierRepository supplierRepository;

    @Override
    public Supplier save(Supplier quality) {
        quality.setCreateTime(new Date());
        quality.setCreateBy( ConcurentCache.getUserName());
        return supplierRepository.save(quality);
    }

    @Override
    public List<Supplier> list() {
        return supplierRepository.findAll();
    }

    @Override
    public Long getNext(Long id) {
        if(id == null){
            Supplier project = supplierRepository.findFirstByOrderByIdDesc();
            if(project != null) {
                return project.getId();
            }
        }
        Supplier project = supplierRepository.findFirstByIdIsAfter(id);
        if(project == null){ project = supplierRepository.findFirstByOrderByIdDesc(); }
        if(project != null){
            return project.getId();
        }
        return null;
    }

    @Override
    public Long getLast(Long id) {
        if(id == null){
            Supplier project = supplierRepository.findFirstByOrderByIdDesc();
            if(project != null) {
                return project.getId();
            }
        }
        else{
            Supplier project = supplierRepository.findFirstByIdBeforeOrderByIdDesc(id);
            if(project == null){ project = supplierRepository.findFirstByOrderById(); }
            if(project != null){
                return project.getId();
            }
        }
        return null;
    }


    @Override
    public Supplier get(Long id) {
        return supplierRepository.getOne(id);
    }

    @Override
    public Supplier get(String cvencode) {
        return supplierRepository.findSupplierByCvencode(cvencode);
    }

    @Override
    public void del(Long id) {
        supplierRepository.deleteById(id);
    }

    @Override
    public Page<Supplier> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return supplierRepository.findAll(request);
        }
        return supplierRepository.findSuppliersByCvenname(query.getName(), request);
    }
}
